package com.googlecode.monitoring.db.dao;

import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Author: Sergiy Doroshenko
 * Date: May 19, 2010
 * Time: 1:10:52 PM
 */
public class JdbcTableReaderDao implements TableReaderDao {

	private JdbcTemplate jdbcTemplate;


	public JdbcTableReaderDao(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	/**
	 * @param tableName  name of table
	 * @param columnName name of column
	 * @return  list of last three dates
	 */
	public List<Date> getLatestDate(String tableName, String columnName) {

		StringBuilder sql = new StringBuilder("select * from (select ");
		sql.append(columnName);
		sql.append(" from ");
		sql.append(tableName);
		sql.append(" order by ");
		sql.append(columnName);
		sql.append(" desc) where rownum <= 3 order by ");
		sql.append(columnName);
		if (tableName.equals("AARLIGFONDSAVKASTNING")) {
			List<Date> dates = new ArrayList<Date>(3);
			List<Integer> years = this.jdbcTemplate.queryForList(sql.toString(), Integer.class);
			for (Integer year : years) {
				Calendar date = Calendar.getInstance();
				date.set(year, Calendar.JANUARY, 1);
				dates.add(date.getTime());
			}
			return dates;
		}
		List<Date> dates = this.jdbcTemplate.queryForList(sql.toString(), Date.class);
		return dates;
	}

	/**
	 * @param tableName name of table
	 * @return count rows in table tableName
	 */
	public int getLatestDate(String tableName) {

		StringBuilder sql = new StringBuilder("select ");
		sql.append(" count(*) ");
		sql.append(" from ");
		sql.append(tableName);

		int count = this.jdbcTemplate.queryForInt(sql.toString());
		return count;
	}
}
